<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category WebSwoole.php
 * @Depiction webswoole 配置
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/4  16:53
 * +--------------------------------------------------------+
 */

namespace App\Services\Swoole;


class WebSwoole
{

    private $ws;
    private $start_t;
    private $end_t;

    public function start()
    {
        // 创建websocket服务器对象，监听0.0.0.0:9502端口
        $this->ws = new \swoole_websocket_server("0.0.0.0", 9502);
        // $this->ws = new \Swoole\WebSocket\Server("0.0.0.0", 9502);

        // ssl证书
        // $this->ws = new \swoole_websocket_server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);

        $this->ws->set([
            'worker_num'               => 4,
            'heartbeat_check_interval' => 60, // 60秒检测一次
            'heartbeat_idle_time'      => 120, // 120秒没活动的
            // 'ssl_key_file'             => '/usr/local/nginx/conf/ssl/han920.com/2_han920.com.key',
            // 'ssl_cert_file'            => '/usr/local/nginx/conf/ssl/han920.com/1_han920.com_bundle.crt',
        ]);

        $service = app('App\Services\Swoole\WebSwooleService');

        // 监听WebSocket连接打开事件
        $this->ws->on('open', [$service, 'onOpen']);

        // 监听WebSocket消息事件
        $this->ws->on('message', [$service, 'onMessage']);

        // 监听WebSocket主动推送消息事件
        $this->ws->on('request', function ($request, $response) use ($service) {
            $service->onRequest($request, $response, $this->ws);
        });

        // 监听WebSocket连接关闭事件
        $this->ws->on('close', [$service, 'onClose']);

        $this->ws->start();
    }


    public function reload()
    {
        $this->ws = new \swoole_websocket_server("0.0.0.0", 9502);
        $this->ws->reload();
        //         \swoole_server::reload();
    }

}
